<template>
    <div class="index-lists">
        <el-card class="!border-none" shadow="never">
            <el-form ref="formRef" class="mb-[-16px]" :model="queryParams" :inline="true">
                <el-form-item label="" style="float: left">
                    <el-select class="w-[280px]" clearable v-model="queryParams.deviceId" filterable placeholder="设备名称">
                        <el-option
                            v-for="(item, index) in optionsData.allDevice"
                            :key="index" :label="item.deviceName" :value="item.id"/>
                    </el-select>
                </el-form-item>
                <div style="float: left" v-if="pass_flag">
                    <el-form-item label="" >
                        <el-select
                            v-model="queryParams.deviceControlType"
                            class="w-[280px]"
                            clearable
                            placeholder="参数类型"
                        >
                            <el-option v-for="(item, index) in dictData.device_control_type" :key="index" :label="item.name"
                                       :value="item.value"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item v-if="switchFlag === 'CZQXQH(R/W)'" label="">
                        <el-radio-group v-model="queryParams.controlValue">
                            <el-radio :label="1">自动</el-radio>
                            <el-radio :label="0">手动</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item v-else-if="switchFlag === 'TSBQT(R/W)'" label="">
                        <el-radio-group v-model="queryParams.controlValue">
                            <el-radio :label="1">开启</el-radio>
                            <el-radio :label="0">关闭</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item v-else-if="switchFlag === 'NJBQT(R/W)'" label="">
                        <el-radio-group v-model="queryParams.controlValue">
                            <el-radio :label="1">开启</el-radio>
                            <el-radio :label="0">关闭</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item v-else label="">
                        <el-input class="w-[280px]" v-model="queryParams.controlValue" type="number" placeholder="参数值"/>
                    </el-form-item>
                    <el-form-item>
                        <el-button v-if="start_test === 'stopTest'" type="primary" @click="startTest">开始检测</el-button>
                        <el-button v-else type="danger" @click="startTest">停止检测</el-button>
                        <el-button type="warning" @click="updateControlTypeClick" :disabled="updateFlag">发送</el-button>
<!--                        <el-button @click="resetParams">重置</el-button>-->
                        <el-button type="primary" @click="resetPage">刷新</el-button>
                    </el-form-item>
                </div>
                <div style="float: left" v-else>
                    <el-form-item label="">
                        <el-input class="w-[280px]" v-model="queryParams.password" type="password" placeholder="请输入密码"/>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSubmit">确认</el-button>
                    </el-form-item>
                </div>
            </el-form>
        </el-card>
        <el-card class="!border-none mt-4" shadow="never">
            <el-table
                class="mt-4"
                size="large"
                v-loading="pager.loading"
                :data="pager.lists"
            >
                <el-table-column label="设备mac地址" prop="address" min-width="100"/>
                <el-table-column label="设备客户端名称" prop="clientId" min-width="100"/>
                <el-table-column label="发送/接受" prop="sendTypeText" min-width="100"/>
                <el-table-column label="创建时间" prop="createTime" min-width="100"/>
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="{ row }">
                        <el-button
                            type="primary"
                            link
                            @click="handleEdit(row)"
                        >
                            详情
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists"/>
            </div>
        </el-card>
        <edit-popup
            v-if="showEdit"
            ref="editRef"
            @success="getLists"
            @close="showEdit = false"
        />
    </div>
</template>
<script lang="ts" setup name="consumerLists">
import {usePaging} from '@/hooks/usePaging'
import {getRoutePath} from '@/router'
import {
    deviceMessageLists2,
    allDevice,
    updateControlType,
    deviceMessageStartTest,
    startTestInfo
} from '@/api/device_test'
import {useDictData, useDictOptions} from "@/hooks/useDictOptions";
import EditPopup from './edit.vue'
import {ref} from "vue";
import feedback from "@/utils/feedback";
import {effect} from "@/api/devicebysite";

const editRef = shallowRef<InstanceType<typeof EditPopup>>()
const showEdit = ref(false)
const timer = ref(); // 定时器
const start_test = ref(""); // 开始检测startTest/停止检测stopTest
const pass_flag = ref(false);

const queryParams = reactive({
    deviceId: '',
    address: '',
    clientId: '',
    messageJson: '',
    deviceControlType: '',
    controlValue: '',
    sendType: '',
    password: ''
})

const updateFlag = computed(() => {
    if (queryParams.deviceId === undefined || queryParams.deviceId === '') {
        return true
    }
    if (queryParams.deviceControlType === undefined || queryParams.deviceControlType === '') {
        return true
    }
    if (queryParams.controlValue === undefined || queryParams.controlValue === '') {
        return true
    }
    if (start_test.value != 'startTest') {
        return true
    }
    console.log("---")
    return false
})

const switchFlag = computed(() => {
    if (queryParams.deviceControlType === 'CZQXQH(R/W)'
        || queryParams.deviceControlType === 'TSBQT(R/W)'
        || queryParams.deviceControlType === 'NJBQT(R/W)') {
        return queryParams.deviceControlType
    } else {
        return 'value'
    }
})

// 监视 对象的某个基本类型属性
watch(() => queryParams.deviceId, async (newValue, oldValue) => {
    console.log('deviceId变了', newValue, oldValue)
    if (oldValue !== '' && start_test.value === 'startTest') {
        stopTest(oldValue);
    }
    pager.lists = [];
    queryParams.deviceControlType = '';
    queryParams.controlValue = '';
    pass_flag.value = false;
})

const {dictData} = useDictData<{
    device_control_type: any[],
    send_type: any[],
}>(['device_control_type', 'send_type'])

const {optionsData} = useDictOptions<{
    allDevice: any[]
}>({
    allDevice: {
        api: allDevice
    }
})

const {pager, getLists, resetPage, resetParams} = usePaging({
    fetchFun: deviceMessageLists2,
    params: queryParams
})


const handleEdit = async (data: any) => {
    showEdit.value = true
    await nextTick()
    editRef.value?.open('edit')
    editRef.value?.getDetail(data)
}

const stopTest = async (deviceId: any) => {
    const data: any = {start: 'stopTest', deviceId: deviceId}
    const msg = await deviceMessageStartTest(data)
    feedback.msgSuccess(msg.startTestMsg);
    start_test.value = msg.startTest;
}

const startTest = async () => {
    if (queryParams.deviceId === '') {
        feedback.alertWarning("请选择检测设备")
        return
    }
    if (start_test.value === 'startTest') {
        start_test.value = 'stopTest';
    } else {
        start_test.value = 'startTest';
    }
    const data: any = {start: start_test.value, deviceId: queryParams.deviceId}
    const msg = await deviceMessageStartTest(data)
    console.log("---------", msg);
    feedback.msgSuccess(msg.startTestMsg);
    start_test.value = msg.startTest;

}

const updateControlTypeClick = async () => {
    const data: any = {...queryParams}
    const msg = await updateControlType(data)
    feedback.msgSuccess('操作成功')
    feedback.alertSuccess(msg.sendJson);
    getLists();
}


// 循环请求接口
const verification = () => {
    timer.value = setInterval(() => {
        getLists();
    }, 15000);
}

const getStartTestInfo = async () => {
    const data = await startTestInfo();
    start_test.value = data.startTest;
    queryParams.deviceId = data.deviceId;
    if (start_test.value === '') {
        start_test.value = 'stopTest'
    }
}

const handleSubmit = async () => {
    console.log("-----", queryParams.deviceId);
    if (queryParams.deviceId === '') {
        feedback.alertWarning("请选择检测设备")
        return;
    }
    let device = optionsData.allDevice.filter(item=> item.id === queryParams.deviceId)[0]
    const data= await effect({
        address: device.address,
        devicePassword: queryParams.password
    })
    if(data.address!=null){
        feedback.msgSuccess('操作成功')
        queryParams.password = '';
        pass_flag.value = true;
    }else{
        feedback.msgError('密码错误')
        pass_flag.value = false;
    }
}

onMounted(() => {
    getStartTestInfo();
})

onUnmounted(() => {
    if (start_test.value === 'startTest') {
        stopTest(queryParams.deviceId);
    }
    clearInterval(timer.value);
    timer.value = null;
})

watch(start_test, (newValue) => {
    if (newValue === 'stopTest') {
        clearInterval(timer.value);
    } else {
        verification();
    }
})

getLists()

</script>
